from flask import g
from sqlalchemy.orm import relationship
from .base import Base, db
from sqlalchemy import Integer, Column, Text, String, ForeignKey


class Blog(Base):
    id = Column(Integer, primary_key=True, autoincrement=True)
    title = Column(String(24), nullable=True)
    author = Column(String(24), nullable=True)
    content = Column(Text, nullable=True)
    read_count = Column(Integer, default=0)
    like_count = Column(Integer, default=0)
    comment_count = Column(Integer, default=0)
    comments = relationship("Comment")


class Like(Base):
    id = Column(Integer, primary_key=True, autoincrement=True)
    blogs_id = Column(Integer, ForeignKey('blog.id'), nullable=True)
    user_id = Column(Integer, ForeignKey('user.id'))

    def add_like(self, form_data):
        with db.auto_commit():
            self.blogs_id = form_data['blogs_id']
            self.user_id = g.user.uid
            blog = Blog.query.get(form_data['blogs_id'])
            blog.like_count += 1
            db.session.add(self)

    def delect_like(self, form_data):
        with db.auto_commit():
            like = Like.query.filter_by(blog_id=form_data.blogs_id.data, user_id=g.user.uid).first()
            db.session.delete(like)
            blog = Blog.query.get(form_data['blogs_id'])
            if blog.like_count > 0:
                blog.like_count -= 1


class Comment(Base):
    id = Column(Integer, primary_key=True, autoincrement=True)
    blogs_id = Column(Integer, ForeignKey('blog.id'), nullable=True)
    user_id = Column(Integer, nullable=True)
    content = Column(Text, nullable=True)
    parent_id = Column(Integer, nullable=False, default=None)

    def __init__(self):
        self.fields = ['id', 'content', 'parent_id']
